const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs'
};

async function checkCasinoRoundsData() {
    let connection;

    try {
        console.log('🔌 正在连接数据库...');
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功！\n');

        // 检查casino_rounds表的数据
        console.log('📊 检查casino_rounds表数据...\n');

        const [rounds] = await connection.execute(`
      SELECT 
        id,
        gameType,
        roundNumber,
        startTime,
        endTime,
        status,
        resultData,
        totalGold,
        totalSilver,
        createdAt,
        updatedAt
      FROM casino_rounds 
      ORDER BY createdAt DESC 
      LIMIT 20
    `);

        if (rounds.length === 0) {
            console.log('❌ casino_rounds表没有数据');
            return;
        }

        console.log(`✅ 找到 ${rounds.length} 条期数记录\n`);

        // 分析每条记录
        for (const round of rounds) {
            const statusText = getStatusText(round.status);
            const gameTypeText = getGameTypeText(round.gameType);
            const resultDataText = round.resultData ? JSON.stringify(round.resultData) : 'NULL';

            console.log(`🔍 期数ID: ${round.id}`);
            console.log(`   游戏类型: ${gameTypeText} (${round.gameType})`);
            console.log(`   期数编号: ${round.roundNumber}`);
            console.log(`   开始时间: ${round.startTime}`);
            console.log(`   结束时间: ${round.endTime}`);
            console.log(`   状态: ${statusText} (${round.status})`);
            console.log(`   开奖结果: ${resultDataText}`);
            console.log(`   总金币: ${round.totalGold}`);
            console.log(`   总银币: ${round.totalSilver}`);
            console.log(`   创建时间: ${round.createdAt}`);
            console.log(`   更新时间: ${round.updatedAt}`);

            // 检查时间逻辑
            const now = new Date();
            const startTime = new Date(round.startTime);
            const endTime = new Date(round.endTime);
            const isExpired = now > endTime;
            const isActive = round.status === 0; // 下注中

            if (isExpired && isActive) {
                console.log(`   ⚠️  问题: 期数已过期但仍在下注状态！`);
            }

            if (round.status === 2 && !round.resultData) { // 已结算但无开奖结果
                console.log(`   ❌ 问题: 期数已结算但开奖结果为空！`);
            }

            console.log('');
        }

        // 统计状态分布
        console.log('📈 期数状态统计:');
        const [statusStats] = await connection.execute(`
      SELECT 
        status,
        COUNT(*) as count,
        MIN(createdAt) as earliest,
        MAX(createdAt) as latest
      FROM casino_rounds 
      GROUP BY status
      ORDER BY status
    `);

        statusStats.forEach(stat => {
            const statusText = getStatusText(stat.status);
            console.log(`   ${statusText} (${stat.status}): ${stat.count} 个`);
            console.log(`     最早: ${stat.earliest}, 最晚: ${stat.latest}`);
        });

        console.log('');

        // 检查是否有问题的期数
        console.log('🔍 检查问题期数...');

        // 1. 已过期但仍在下注状态的期数
        const [expiredActiveRounds] = await connection.execute(`
      SELECT COUNT(*) as count 
      FROM casino_rounds 
      WHERE status = 0 AND endTime < NOW()
    `);

        if (expiredActiveRounds[0].count > 0) {
            console.log(`   ⚠️  发现 ${expiredActiveRounds[0].count} 个已过期但仍在下注状态的期数`);
        } else {
            console.log(`   ✅ 没有过期的活跃期数`);
        }

        // 2. 已结算但无开奖结果的期数
        const [settledNoResultRounds] = await connection.execute(`
      SELECT COUNT(*) as count 
      FROM casino_rounds 
      WHERE status = 2 AND (resultData IS NULL OR resultData = '')
    `);

        if (settledNoResultRounds[0].count > 0) {
            console.log(`   ❌ 发现 ${settledNoResultRounds[0].count} 个已结算但无开奖结果的期数`);
        } else {
            console.log(`   ✅ 所有已结算期数都有开奖结果`);
        }

        // 3. 检查定时任务执行情况
        console.log('\n⏰ 检查定时任务执行情况...');

        const [recentRounds] = await connection.execute(`
      SELECT 
        gameType,
        COUNT(*) as count,
        MIN(createdAt) as earliest,
        MAX(createdAt) as latest
      FROM casino_rounds 
      WHERE createdAt >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
      GROUP BY gameType
      ORDER BY gameType
    `);

        if (recentRounds.length > 0) {
            console.log('   最近1小时创建的期数:');
            recentRounds.forEach(round => {
                const gameTypeText = getGameTypeText(round.gameType);
                console.log(`     ${gameTypeText}: ${round.count} 个`);
                console.log(`       时间范围: ${round.earliest} ~ ${round.latest}`);
            });
        } else {
            console.log('   ⚠️  最近1小时没有创建新期数');
        }

        // 4. 检查下注数据
        console.log('\n💰 检查下注数据...');

        const [betStats] = await connection.execute(`
      SELECT 
        r.id,
        r.gameType,
        r.status,
        COUNT(d.id) as diceBets,
        COUNT(c.id) as chibiBets,
        COALESCE(SUM(d.betAmount), 0) as totalDiceBet,
        COALESCE(SUM(c.betGold + c.betSilver), 0) as totalChibiBet
      FROM casino_rounds r
      LEFT JOIN casino_dice_bets d ON r.id = d.roundId
      LEFT JOIN casino_chibi_bets c ON r.id = c.roundId
      GROUP BY r.id, r.gameType, r.status
      ORDER BY r.createdAt DESC
      LIMIT 10
    `);

        if (betStats.length > 0) {
            console.log('   最近10个期数的下注统计:');
            betStats.forEach(stat => {
                const gameTypeText = getGameTypeText(stat.gameType);
                const statusText = getStatusText(stat.status);
                console.log(`     期数${stat.id} (${gameTypeText} - ${statusText}):`);
                console.log(`       大小下注: ${stat.diceBets} 笔, 总金额: ${stat.totalDiceBet}`);
                console.log(`       赤壁下注: ${stat.chibiBets} 笔, 总金额: ${stat.totalChibiBet}`);
            });
        }

    } catch (error) {
        console.error('❌ 检查过程中发生错误:', error.message);
    } finally {
        if (connection) {
            await connection.end();
            console.log('\n🔌 数据库连接已关闭');
        }
    }
}

function getStatusText(status) {
    const statusMap = {
        0: '下注中',
        1: '开奖中',
        2: '已结算'
    };
    return statusMap[status] || `未知状态(${status})`;
}

function getGameTypeText(gameType) {
    const gameTypeMap = {
        1: '大小玩法',
        2: '赤壁玩法',
        3: '猜拳玩法'
    };
    return gameTypeMap[gameType] || `未知类型(${gameType})`;
}

// 运行检查
checkCasinoRoundsData().catch(console.error); 